﻿using czj_shop.Models;
using czj_shop.Models.Database;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace czj_shop.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly czj_shopContext _db;
        private readonly IJWTService _jwtService;
        public UserController(czj_shopContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }
        [HttpPost]
        public string AddUser(AddUserRequest request)
        {
            //接口的具体实现
            //二次确认密码
            if (request.Password != request.CifrgPassword)
                return "两次输入不一致";

            //手机号不能重复
            if (_db.Users.Any(x => x.Phone == request.Mobile))
                return "手机号码已存在";

            //添加一个新的用户
            var user = new User
            {
                Createtime = DateTime.Now,
                Phone = request.Mobile,
                Pwd = request.Password,
                Name = string.Empty,
                Pic = string.Empty,
            };

            _db.Users.Add(user);
            //保存更改 增加 修改 删除
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }
        /// <summary>
        /// 用户登录接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //用户登录接口（用户使用手机号码，密码进行登录，登录后可访问需要授权的页面） 输入：用户手机号码，密码 输出：登录成功返回token,失败提示消息
        [HttpPost]
        public string Login(LoginRequest request)
        {
            //查询数据库手机号码为输入的手机号的用户
            var user = _db.Users.FirstOrDefault(x => x.Phone == request.Mobile);
            if (user == null)
                return "用户不存在";

            //char 固定长度字符串char30
            //如果用户存在
            //"123456"                "123456             "
            if (request.Password != user.Pwd)
                return "输入的密码不正确";


            //创建token
            return _jwtService.CreateToken(user.Id, user.Name);
        }

        //个人中心接口（需授权） 输入：无（根据授权返回） 输出：用户各订单状态数量，用户头像，用户昵称（如果没有设置昵称用手机号码代替）
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public GetUserInfoResponse GetUserInfo()
        {
            //获取登录用户信息
            var Id = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var user = _db.Users.FirstOrDefault(x => x.Id == Convert.ToInt32(Id));
            if (user == null)
                return null;

            return new GetUserInfoResponse
            {
                Photo = user.Pic,
                NickName = user.Name
            };
        }

        //修改用户信息接口（需授权） 输入：用户头像，用户昵称 输出：消息
        /// <summary>
        /// 修改用户信息接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public string UpdateUserInfo(UpdateUserInfoRequest request)
        {
            //修改哪个用户？？
            //登录用户
            //获取登录用户信息
            var Id = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var user = _db.Users.FirstOrDefault(x => x.Id == Convert.ToInt32(Id));
            if (user == null)
                return null;

            user.Name = request.NickName;
            user.Pic = request.Photo;
            _db.Users.Update(user);
            var row = _db.SaveChanges();
            if (row > 0)
                return "修改成功";
            return "修改失败";
        }
    }
}
